<?
include("inc_security.php");

//Call class menu
$menu				= new menu();
$listAll			= $menu->getAllChild("categories_multi", "cat_id", "cat_parent_id", 0, "cat_type='news' AND cat_id IN (" . $gs_category . ") AND lang_id = " . $lang_id, "cat_id,cat_name,cat_type,cat_all_child", "cat_order ASC,cat_name ASC", "cat_has_child", 0);
unset($menu);

//Khai báo biến khi hiển thị danh sách
$gs_title		= $module_name . " | Danh sách";
$gs_action		= "listing.php" . getURL(0,0,0,1,"record_id");
$gs_redirect	= "listing.php" . getURL(0,0,0,1,"record_id");
$gs_errorMsg	= "";

/*****----- Quick Edit -----*****/
$action			= getValue("action", "str", "POST", "");
if($action == "quick_edit"){
	
	//Get data edit
	$record_id	= getValue("record_id", "int", "POST", 0);
	$db_edit		= new db_query("SELECT * FROM " . $gs_table . " WHERE " . $id_field . " = " . $record_id . " AND lang_id = " . $lang_id);
	if(mysql_num_rows($db_edit->result) == 0){
		$gs_errorMsg .= "&bull; Không tìm thấy dữ liệu, bạn hãy liên hệ với ban quản trị Website!<br />";
	}
	else{

		$edit		= mysql_fetch_array($db_edit->result);
		unset($db_edit);
		
		//Lấy dữ liệu đề giữ nguyên trạng thái khi submit error
		$new_category_id	= getValue("new_category_id", "int", "POST", $edit["new_category_id"]);
		$new_title			= getValue("new_title", "str", "POST", $edit["new_title"]);
		$new_link			= getValue("new_link", "str", "POST", $edit["new_link"]);
			
		/*
		Call class form:
		1). Ten truong
		2). Ten form
		3). Kieu du lieu , 0 : string , 1 : kieu int, 2 : kieu email, 3 : kieu double, 4 : kieu hash password
		4). Noi luu giu data  0 : post, 1 : variable
		5). Gia tri mac dinh, neu require thi phai lon hon hoac bang default
		6). Du lieu nay co can thiet hay khong
		7). Loi dua ra man hinh
		8). Chi co duy nhat trong database
		9). Loi dua ra man hinh neu co duplicate
		*/
		$myform = new generate_form();
		//Add table insert data
		$myform->addTable($gs_table);
		if(strpos($gs_category, $new_category_id . ",") === false){
			$gs_errorMsg .= "&bull; Bạn không được phép truy cập category này!<br />";
		}
		$myform->add("new_category_id", "new_category_id", 1, 1, 1, 1, "Bạn chưa chọn danh mục tin.", 0, "");
		$myform->add("new_title", "new_title", 0, 1, " ", 1, "Bạn chưa nhập tiêu đề tin.", 0, "");
		$myform->add("new_link", "new_link", 0, 1, "", 0, "", 0, "");
		
		//Check form data
		$gs_errorMsg .= $myform->checkdata();
		
		//Get $filename
		$filename		= "";
		if($gs_errorMsg == ""){
			$upload		= new upload($gs_fieldupload, $gs_filepath, $gs_extension, $gs_filesize, $gs_insert_logo);
			$filename	= $upload->file_name;
			$gs_errorMsg .= $upload->warning_error;
		}
		
		if($gs_errorMsg == ""){
			
			if($filename != ""){
				//Xóa ảnh cũ đi
				if($edit[$gs_fieldupload] != "") $upload->delete_file($gs_filepath, $edit[$gs_fieldupload]);
				//Upload new image
				$$gs_fieldupload = $filename;
				$myform->add($gs_fieldupload, $gs_fieldupload, 0, 1, "", 0, "", 0, "");
				$upload->resize_image($gs_filepath, $filename, $width_small_image, $height_small_image, "small_");
			}//End if($filename != "")
			
			//Update to database
			$myform->removeHTML(0);
			$db_update = new db_execute($myform->generate_update_SQL($id_field, $record_id));
			unset($db_update);
			
		}//End if($gs_errorMsg == "")
		unset($myform);
	
	}
	
	if($gs_errorMsg != ""){
		$arr_str		= array("&bull; ", "<br />");
		$arr_rep		= array("- ", "\\n");
		$gs_errorMsg= str_replace($arr_str, $arr_rep, $gs_errorMsg);
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
		echo '<script language="javascript">alert("Có những lỗi sau:\\n' . $gs_errorMsg . '")</script>';
	}
	
	//Redirect
	redirect($gs_redirect);
	
}
/*****----- End Quick Edit -----*****/

$record_id	= getValue("record_id");

//Search data
$id			= getValue("id");
$keyword		= getValue("keyword", "str", "GET", "", 1);
$date			= getValue("date", "dbl");
$show			= getValue("show");
$category	= getValue("category");
$sqlWhere	= "";
//Tìm theo ID
if($id > 0)			$sqlWhere .= " AND new_id = " . $id . " ";
//Tìm theo keyword
if($keyword != ""){
	if(validateDate($keyword) == 1){
		$startTime	= convertDateTime($keyword, "00:00:00");
		$endTime		= convertDateTime($keyword, "23:59:59");
		$sqlWhere	.= " AND new_date >= " . $startTime . " AND new_date <= " . $endTime . " ";
	}
	else{
		$sqlWhere	.= " AND (new_title LIKE '%" . $keyword . "%' OR new_teaser LIKE '%" . $keyword . "%' OR new_link LIKE '%" . $keyword . "%') ";
	}
}
//Tìm theo số ngày cập nhật
if($date > 0)		$sqlWhere .= " AND new_date > " . ($gs_today[0] - $date * 86400) . " ";
//Tìm theo show
if($show > 0){
	switch($show){
		case 1:	$sqlWhere .= " AND new_picture <> '' "; break;
		case 2:	$sqlWhere .= " AND new_picture IS NULL "; break;
		case 3:	$sqlWhere .= " AND new_active = 1 "; break;
		case 4:	$sqlWhere .= " AND new_active = 0 "; break;
		case 5:	$sqlWhere .= " AND new_post = 1 "; break;
		case 6:	$sqlWhere .= " AND new_post = 0 "; break;
	}
}
//Tìm theo category
if($category > 0){
	$db_cat	= new db_query("SELECT cat_all_child FROM categories_multi WHERE cat_id = " . $category);
	if($row	= mysql_fetch_array($db_cat->result)) $sqlWhere .= " AND cat_id IN (" . $row["cat_all_child"] . ") ";
	unset($db_cat);
}

//Sort data
$sort			= getValue("sort");
switch($sort){
	case 1: $sqlOrderBy = "new_title ASC"; break;
	case 2: $sqlOrderBy = "new_title DESC"; break;
	case 3: $sqlOrderBy = "new_date ASC"; break;
	case 4: $sqlOrderBy = "new_date DESC"; break;
	case 5: $sqlOrderBy = "nh_hits ASC"; break;
	case 6: $sqlOrderBy = "nh_hits DESC"; break;
	default:$sqlOrderBy = "new_date DESC"; break;
}

//Get page break params
$page_size		= 20;
$page_prefix	= "Trang: ";
$normal_class	= "page";
$selected_class= "page_current";
$previous		= "<";
$next				= ">";
$first			= "<<";
$last				= ">>";
$break_type		= 1;//"1 => << < 1 2 [3] 4 5 > >>", "2 => < 1 2 [3] 4 5 >", "3 => 1 2 [3] 4 5", "4 => < >"
$url				= getURL(0,0,1,1,"page");
$db_count		= new db_query("SELECT COUNT(*) AS count
										 FROM (categories_multi, " . $gs_table . ") INNER JOIN news_hits ON new_id = nh_id
									 	 WHERE cat_id = new_category_id AND cat_id IN (" . $gs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere);
$listing_count	= mysql_fetch_array($db_count->result);
$total_record	= $listing_count["count"];
$current_page	= getValue("page", "int", "GET", 1);
if($total_record % $page_size == 0) $num_of_page = $total_record / $page_size;
else $num_of_page = (int)($total_record / $page_size) + 1;
if($current_page > $num_of_page) $current_page = $num_of_page;
if($current_page < 1) $current_page = 1;
$db_count->close();
unset($db_count);
//End get page break params
$db_listing	= new db_query("SELECT cat_id, cat_name, cat_type, new_id, new_title, new_picture, new_date, new_link, new_active, nh_hits
									 FROM (categories_multi, " . $gs_table . ") INNER JOIN news_hits ON new_id = nh_id
									 WHERE cat_id = new_category_id AND cat_id IN (" . $gs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere . "
									 ORDER BY " . $sqlOrderBy . "
									 LIMIT " . ($current_page - 1) * $page_size . ", " . $page_size);
?>
<html>
<head>
<title><?=$gs_title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css" media="all">@import "../css/GSportal.css";</style>
<script language="javascript" src="../js/library.js"></script>
<script language="javascript" src="../js/tooltip.js"></script>
</head>
<body>
<div class="bg_title_content">
<div class="content_title" style="float:left"><?=$gs_title?>: <font class="count"><?=format_number($total_record)?></font></div>
<div class="content_title" style="float:right"><a title="Thêm mới" href="add.php?category=<?=$category?>"><img align="absmiddle" border="0" hspace="5" src="<?=$gs_imagepath?>add.gif" />Thêm mới</a></div>
</div>
<div align="center" class="content">
<? //Page break and search data?>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
	<?	if($total_record > $page_size){?>
		<td nowrap="nowrap"><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?></td>
	<? }?>
		<td align="right">
			<table cellpadding="0" cellspacing="0">
			<form name="search" action="<?=getURL(0,0,1,0)?>" method="get">
				<tr>
					<td class="form_search" nowrap="nowrap">
						ID:
						<input title="ID" type="text" class="form_control" id="id" name="id" value="<?=$id?>" maxlength="11" style="width:80px; text-align:right">&nbsp;
						Từ khóa:
						<input title="Từ khóa" type="text" class="form_control" id="keyword" name="keyword" value="<?=$keyword?>" maxlength="255" style="width:100px">&nbsp;
						Ngày:
						<input title="Số ngày cập nhật gần đây" type="text" class="form_control" id="date" name="date" value="<?=$date?>" maxlength="11" style="width:50px; text-align:right">&nbsp;
						<select title="Kiểu hiển thị tin" name="show" class="form_control">
							<option value="0">--[Hiển thị tin]--</option>
						<?
						$arrShow = array(1 => "Có ảnh", 2 => "Không có ảnh", 3 => "Kích hoạt", 4 => "Không kích hoạt", 5 => "Tin tự nhập", 6 => "Tin lấy tự động");
						foreach($arrShow as $key => $value){
						?>
							<option title="<?=$value?>" value="<?=$key?>" <? if($key == $show){echo 'selected="selected"';}?>><?=$value?></option>
						<?
						}
						?>
						</select>
						<select title="Hiển thị theo danh mục" name="category" class="form_control">
							<option value="">--[Tất cả các mục]--</option>
						<?
						for($i=0; $i<count($listAll); $i++){
							$db_count	= new db_query("SELECT COUNT(*) AS count FROM " . $gs_table . " WHERE new_category_id IN (" . $listAll[$i]["cat_all_child"] . ") AND lang_id = " . $lang_id);
							$row = mysql_fetch_array($db_count->result);
							unset($db_count);
						?>
							<option title="<?=$listAll[$i]["cat_name"]?> (<?=format_number($row["count"])?>)" value="<?=$listAll[$i]["cat_id"]?>" <? if($listAll[$i]["cat_id"] == $category){echo 'selected="selected"';}?>>
							<?
							for($j=0; $j<$listAll[$i]["level"]; $j++) echo " |--";
							echo " " . $listAll[$i]["cat_name"] . " (" . format_number($row["count"]). ")";
							?>
							</option>
						<?
						}// End for($i=0; $i<count($listAll); $i++)
						?>
						</select>
						<input type="hidden" name="sort" value="<?=$sort?>" />
					</td>
					<td class="form_search" style="padding-left:5px"><input title="Tìm kiếm" type="image" src="<?=$gs_imagepath?>search.gif" border="0"></td>
				</tr>
			</form>
			</table>
		</td>
	</tr>
</table>
<? //End page break and search data?>
<table class="table" border="1" bordercolor="#e5e3e6" cellpadding="3" cellspacing="0" width="98%">
	<tr class="table_title_3">
		<td>Stt.</td>
		<td>Ảnh</td>
		<td>Danh mục tin</td>
		<td>
			<div>Tiêu đề tin</div>
			<div>
				<?=generate_sort("asc", 1, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 2, $sort, $gs_imagepath)?>
			</div>
		</td>
		<td>
			<div>Cập nhật</div>
			<div>
				<?=generate_sort("asc", 3, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 4, $sort, $gs_imagepath)?>
			</div>
		</td>
		<td nowrap="nowrap">
			<div>Lượt xem</div>
			<div>
				<?=generate_sort("asc", 5, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 6, $sort, $gs_imagepath)?>
			</div>
		</td>
		<td>Kích<br />hoạt</td>
        <td>Xem</td>
        <td>Lưu</td>
        <td>Sửa</td>
        <td>Xóa</td>
	</tr>
<?
//Call class form
$form = new form();
$form->class_form_name = "form_name_2";
?>
<?
$record_id = getValue("record_id", "int", "POST");
//Đếm số thứ tự
$No = ($current_page - 1) * $page_size;
while($listing = mysql_fetch_array($db_listing->result)){
	$No++;
	$preview_link	= generate_detail_url($listing["cat_type"], $listing["cat_id"], $listing["new_id"], $listing["new_title"]);
?>
	<?
	$form->create_form("quick_edit_" . $No, $gs_action, "post", "multipart/form-data");
	?>
	<tr id="tr_<?=$No?>" <?=$gs_change_bg?>>
		<td class="No"><?=$No?></td>
		<td align="center">
			<div class="image_style">
			<? if($listing["new_picture"] != ""){?>
				<a title="<?=htmlspecialbo($listing["new_title"])?>" href="<?=$preview_link?>" target="_blank" onMouseOver="showtip('<img src=\'<?=$gs_filepath?><?=$listing["new_picture"]?>\' />')" onMouseOut="hidetip()"><img src="<?=$gs_filepath?>small_<?=$listing["new_picture"]?>" onError="this.src='<?=$gs_no_image?>'" /></a>
			<? }else{?>
				<a title="<?=htmlspecialbo($listing["new_title"])?>" href="<?=$preview_link?>" target="_blank"><img class="style_image" width="40" src="<?=$gs_no_image?>" /></a>
			<? }?>
			</div>
			<? if($listing["new_picture"] != ""){?><div style="margin-top:3px"><a href="javascript:if(confirm('Bạn có muốn xóa ảnh này không?')){window.location.href='delete.php?type=picture&record_id=<?=$listing["new_id"]?>&redirect=<?=base64_encode(getURL())?>'}">[Xóa ảnh]</a></div><? }?>
		</td>
		<td align="center">
			<select title="Danh mục tin" id="new_category_id_<?=$No?>" name="new_category_id" class="form_control">
				<option value="">--[Danh mục tin]--</option>
			<? for($i=0; $i<count($listAll); $i++){?>
				<option title="<?=$listAll[$i]["cat_name"]?>" value="<?=$listAll[$i]["cat_id"]?>" <? if($listAll[$i]["cat_id"] == $listing["cat_id"]){echo 'selected="selected"';}?>>
				<?
				for($j=0; $j<$listAll[$i]["level"]; $j++) echo " |--";
				echo " " . $listAll[$i]["cat_name"];
				?>
				</option>
			<? }?>
			</select>
			<div style="padding-top:5px; color:#FF0000"><?=news_source($listing["new_link"])?></div>
		</td>
		<td align="center">
			<?=$form->create_table(2, 2, "");?>
			<?=$form->text("Tiêu đề", "new_title_" . $No, "new_title", $listing["new_title"], "Tiêu đề tin", 1, 203, "", 255, "", "", "")?>
			<?=$form->getFile("Ảnh", "new_picture_" . $No, "new_picture", "Ảnh minh họa", "0", 23, "", "");?>
			<?=$form->text("Link nguồn", "new_link_" . $No, "new_link", $listing["new_link"], "Link nguồn", 0, 203, "", 255, "", "", "")?>
			<?=$form->close_table();?>
		</td>
		<td align="right">
			<div><?=date("d/m/Y", $listing["new_date"])?></div>
			<div style="color:#666666; font-size:10px"><?=date("H:i A", $listing["new_date"])?></div>
		</td>
		<td class="hits"><?=number_format($listing["nh_hits"],0,".",",")?></td>
		<td align="center"><a href="quickset.php?type=active&record_id=<?=$listing["new_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" src="<?=$gs_imagepath?>active_<?=$listing["new_active"]?>.gif" /></a></td>
        <td align="center">
        	<a title="Xem dữ liệu" href="<?=$preview_link?>" target="_blank"><img border="0" hspace="5" src="<?=$gs_imagepath?>view.gif"></a>
		</td>
		<td align="center">
            <input title="Lưu dữ liệu" type="image" hspace="5" src="<?=$gs_imagepath?>icon_save.gif" onClick="MM_validateForm('new_category_id_<?=$No?>','','R','new_title_<?=$No?>','','R'); return document.MM_returnValue" />
		</td>
		<td align="center">
            <a title="Sửa dữ liệu" href="edit.php?record_id=<?=$listing["new_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" hspace="5" src="<?=$gs_imagepath?>edit.gif"></a>
		</td>
		<td align="center">
            <img title="Xóa dữ liệu" hspace="5" src="<?=$gs_imagepath?>delete.gif" style="cursor:pointer" onClick="if(confirm('Bạn có muốn xóa dữ liệu này không?')){window.location.href='delete.php?record_id=<?=$listing["new_id"]?>&redirect=<?=base64_encode(getURL())?>'}" />
		</td>
	</tr>
	<?=$form->hidden("record_id_" . $No, "record_id", $listing["new_id"], "");?>
	<?=$form->hidden("action_" . $No, "action", "quick_edit", "");?>
	<?
	$form->close_form();
	?>
<?
}// End while($listing = mysql_fetch_array($db_listing->result))
?>
<?
unset($form);
?>
</table>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
    	<? if($total_record > $page_size){?>
		<td><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?></td>
        <? }?>
		<td align="right"><a title="Go to top" accesskey="T" class="top" href="#">Lên trên<img align="absmiddle" border="0" hspace="5" src="<?=$gs_imagepath?>top.gif"></a></td>
	</tr>
</table>
</div>
</body>
</html>
<script language="javascript">ButtonLeftFrame();</script>